#include "BulletEntity.h"




BulletEntity::BulletEntity(int id, int type, double x, double y, int direction, Rect* actor, Rect* target, BulletArmies bulletArmy, bool isHalf, int distanceForLive)
{
	// Init data object
	_data = new BulletData(id, type, x, y, direction, actor, target, bulletArmy, isHalf, distanceForLive);
	_data->initData();
}

void BulletEntity::fire()
{
	// Turn on flag fired to update bullet
	_data->isFired = true;
	_data->rect->Vx = _data->rect->Vy = 0;

	// Check fire exist target
	if (_data->target != NULL) {
		if (_data->isHalf) {
			_behavior->setHalfTargetDirection();
		} else {
			_behavior->setTargetDirection();
		}
	}
	else {
		_behavior->setNonTargetDirection();
	}
}

void BulletEntity::update(long time)
{
	// Bullet not fired return without update anything
	if (!_data->isFired || !checkAlive()) {
		return;
	}
	// Update bullet position by behavior
	_data->sprites->updateCurrent();
	_behavior->update(time);
}

void BulletEntity::setBulletBehavior(BulletBehavior* behavior)
{
	if (behavior != NULL) {
		if (this->_behavior != NULL) {
			//delete this->_behavior;
		}
		this->_behavior = behavior;
	}
}

BulletData* BulletEntity::getBulletData()
{
	return this->_data;
}

void BulletEntity::draw(long time)
{
	if (checkAlive())
		_data->sprites->draw();
}

AbstractData* BulletEntity::getAbstractData()
{
	return _data;
}

void BulletEntity::initData()
{
	// Init behavior object
	_behavior = new BulletBehavior(_data);
}

void BulletEntity::initData(Rect* actorRect, Rect* targetRect)
{
	this->initData();

	_data->actor = actorRect;
	_data->target = targetRect;
}

BulletEntity::~BulletEntity()
{
	delete _data;
	delete _behavior;
}

void BulletEntity::updateData(int action, int action_data)
{
	if (action == ACTIONS_KILL_BULLET) {
		_data->isDead = true;
	}
}

bool BulletEntity::checkAlive()
{
	int bulletX = this->getAbstractData()->getRect()->X;
	int bulletY = this->getAbstractData()->getRect()->Y;
	int actorX = this->getBulletData()->startX;
	int actorY = this->getBulletData()->startY;
	int distanceForLive = this->getBulletData()->distanceForLive;
	return !((abs(bulletX - actorX) >= distanceForLive)
		|| (abs(bulletY - actorY) >= distanceForLive)
		|| this->getAbstractData()->isDead);
}
